package home1ess.passport.service.impl;

import common.exception.ServiceException;
import common.utils.JwtUtils;
import common.web.StatusCode;
import home1ess.passport.dao.repository.IUserRepository;
import home1ess.passport.pojo.param.UserLoginParam;
import home1ess.passport.pojo.param.UserRegParam;
import home1ess.passport.pojo.param.UserUpdatePasswordParam;
import home1ess.passport.pojo.po.UserPO;
import home1ess.passport.pojo.po.UserRegPO;
import home1ess.passport.pojo.vo.UserLoginVO;
import home1ess.passport.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class UserService implements IUserService {

    @Autowired
    private IUserRepository userRepository;

    private String secretKey = "home1essSecretKey";

    @Override
    public void reg(UserRegParam userRegParam) {
        String phoneNumber = userRegParam.getPhoneNumber();
        UserRegPO regPO = userRepository.selectByPhoneNumber(phoneNumber);
        if(regPO != null){
            throw new ServiceException(StatusCode.BAD_REQUEST,"用户已存在");
        }else {
            //存入数据库
            UserRegPO userRegPO = new UserRegPO();
            //注册时默认不是房东和管理员
            userRegPO.setIsAdmin(0);
            userRegPO.setIsHouseholder(0);

            BeanUtils.copyProperties(userRegParam,userRegPO);
            Integer i = userRepository.save(userRegPO);
            if(i==0){
                throw new ServiceException(StatusCode.BAD_REQUEST,"注册失败");
            }
        }
    }
    //修改密码
    @Override
    public void updatePassword(UserUpdatePasswordParam userUpdatePasswordParam) {
        //1.先根据用户名查询用户当前密码
        UserRegPO userRegPO = userRepository.selectByPhoneNumber(userUpdatePasswordParam.getPhoneNumber());
        System.out.println("userRegPO:"+userRegPO);
        //2.先判断两次输入密码是否一致
        if (!userUpdatePasswordParam.getNewPassword().equals(userUpdatePasswordParam.getNewPasswordTwo())){
            throw new ServiceException(StatusCode.BAD_REQUEST,"两次输入密码不一致");
        }
        //3.判断当前密码与输入旧密码是否一致
        if (userUpdatePasswordParam.getOldPassword().equals(userRegPO.getPassword())){
            //4.执行修改
            //获取新密码
            String newPassword = userUpdatePasswordParam.getNewPassword();
            //修改密码
            userRegPO.setPassword(newPassword);
            //保存
            userRepository.updatePassword(userRegPO);

        }else {
            throw new ServiceException(StatusCode.BAD_REQUEST,"旧密码错误!");
        }

    }



    /**
     * 登录的流程梳理
     * 1.验证用户名  出错报"用户名或者密码错误"
     * 2.验证密码  出错报"用户名或者密码错误"
     * 3.判断用户状态
     * 4.生成Token
     * 5.重复登录(两个人同时用一个账号)
     *      1.正常登录
     *      2.判断用户状态是否已经登录，  已经登录  1.登陆失败    2.把登录的踢掉，我来登录
     *          可以把token失效，它继续访问带着token，访问不了了
     *
     * @param userLoginParam
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginParam userLoginParam, HttpServletRequest request) {
        System.out.println("sdadsadsa"+userLoginParam);
        log.debug("login user:{}",userLoginParam);
        String phoneNumber = userLoginParam.getPhoneNumber();
        UserPO userPO =  userRepository.getUserInfoByUserName(phoneNumber);
        System.out.println("userPO"+userPO);
        //1.判断用户是否存在
        if(userPO == null){
            //抛出异常 账号密码错误
            throw new ServiceException(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //2.走到这说明用户名存在，判断密码
        String password = userPO.getPassword();
        if(!password.equals(userLoginParam.getPassword())){
            //账号密码错误
            throw new ServiceException(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //3.判断用户是否启用
//        if(!userPO.getEnable().equals(1)){
//            //用户被禁用
//            throw new ServiceException(StatusCode.USER_DISABLED);
//        }
        //4.生成token
        Map<String, Object> userData = new HashMap<>();
        userData.put("id",userPO.getId());
        userData.put("username",userPO.getPhoneNumber());
        //token不能太长，因为浪费网络带宽和储存空间，绑得越多 解密越慢
        String jwt = JwtUtils.generate(userData, secretKey);

        //5.用户登录日志
        String remoteAddr = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        log.debug("用户[{}]登录成功，IP[{}]，User-Agent[{}]",phoneNumber,remoteAddr,userAgent);

        //todo   权限存入redis
//        List<PermissionPO> permissions = userRepository
//                .getPermissionsByUserId(userPO.getId());


        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setUsername(phoneNumber);
        userLoginVO.setId(userPO.getId());
        userLoginVO.setToken(jwt);

        return userLoginVO;
    }




}





























